<script setup lang="ts">
import { ref, computed } from 'vue';
import { NDrawer, NDrawerContent, NDescriptions, NDescriptionsItem, NTag, NTree, NSpin } from 'naive-ui';
import type { TreeOption } from 'naive-ui';
import { fetchOpsInstanceTree } from '@/service/api';

const visible = ref(false);
const loading = ref(false);
const instanceData = ref<Api.Dataplatform.OpsInstanceTree | null>(null);

const open = async (instanceId: number) => {
  visible.value = true;
  loading.value = true;
  try {
    instanceData.value = await fetchOpsInstanceTree(instanceId);
  } catch (error) {
    window.$message?.error('加载实例树形结构失败');
  } finally {
    loading.value = false;
  }
};

const handleClose = () => {
  visible.value = false;
  instanceData.value = null;
};

// 构建树形数据
const treeData = computed<TreeOption[]>(() => {
  if (!instanceData.value) return [];

  const buildNode = (instance: Api.Dataplatform.OpsInstanceTree): TreeOption => {
    return {
      key: instance.id.toString(),
      label: `${instance.jobName || '未命名'} (ID: ${instance.id})`,
      children: instance.subInstances?.map(sub => buildNode(sub as Api.Dataplatform.OpsInstanceTree))
    };
  };

  return [buildNode(instanceData.value)];
});

// 状态标签
const getStatusTag = (status: string) => {
  const statusMap: Record<string, { type: 'success' | 'error' | 'warning' | 'info'; text: string }> = {
    RUNNING: { type: 'info', text: '运行中' },
    SUCCESS: { type: 'success', text: '成功' },
    FAILED: { type: 'error', text: '失败' },
    STOPPED: { type: 'warning', text: '已停止' }
  };
  return statusMap[status] || { type: 'info', text: status };
};

// 格式化时长
const formatDuration = (duration?: number) => {
  if (!duration) return '-';
  const seconds = Math.floor(duration / 1000);
  const minutes = Math.floor(seconds / 60);
  const hours = Math.floor(minutes / 60);
  if (hours > 0) return `${hours}小时 ${minutes % 60}分钟`;
  if (minutes > 0) return `${minutes}分钟 ${seconds % 60}秒`;
  return `${seconds}秒`;
};

defineExpose({
  open
});
</script>

<template>
  <NDrawer v-model:show="visible" :width="800" placement="right">
    <NDrawerContent title="实例树形结构" closable>
      <NSpin :show="loading">
        <div v-if="instanceData" class="space-y-16px">
          <!-- 实例基本信息 -->
          <NDescriptions bordered :column="2">
            <NDescriptionsItem label="实例ID">
              {{ instanceData.id }}
            </NDescriptionsItem>
            <NDescriptionsItem label="作业名称">
              {{ instanceData.jobName }}
            </NDescriptionsItem>
            <NDescriptionsItem label="状态">
              <NTag :type="getStatusTag(instanceData.status).type">
                {{ getStatusTag(instanceData.status).text }}
              </NTag>
            </NDescriptionsItem>
            <NDescriptionsItem label="触发类型">
              {{ instanceData.triggerType === 'MANUAL' ? '手动' : instanceData.triggerType === 'SCHEDULE' ? '定时' : '依赖' }}
            </NDescriptionsItem>
            <NDescriptionsItem label="开始时间">
              {{ instanceData.startTime || '-' }}
            </NDescriptionsItem>
            <NDescriptionsItem label="结束时间">
              {{ instanceData.endTime || '-' }}
            </NDescriptionsItem>
            <NDescriptionsItem label="执行时长">
              {{ formatDuration(instanceData.duration) }}
            </NDescriptionsItem>
            <NDescriptionsItem label="重试次数">
              {{ instanceData.retryCount || 0 }}
            </NDescriptionsItem>
            <NDescriptionsItem v-if="instanceData.errorMessage" label="错误信息" :span="2">
              <div class="text-red-500">{{ instanceData.errorMessage }}</div>
            </NDescriptionsItem>
          </NDescriptions>

          <!-- 任务树形结构 -->
          <div v-if="instanceData.subInstances && instanceData.subInstances.length > 0">
            <div class="text-16px font-bold mb-12px">子任务列表</div>
            <NTree
              :data="treeData"
              block-line
              expand-on-click
              :default-expanded-keys="[instanceData.id.toString()]"
            />
          </div>

          <!-- 子任务详情 -->
          <div v-if="instanceData.subInstances && instanceData.subInstances.length > 0">
            <div class="text-16px font-bold mb-12px">子任务详情</div>
            <div class="space-y-12px">
              <NCard
                v-for="subInstance in instanceData.subInstances"
                :key="subInstance.id"
                size="small"
                :title="`${subInstance.jobName} (ID: ${subInstance.id})`"
              >
                <NDescriptions bordered :column="2" size="small">
                  <NDescriptionsItem label="状态">
                    <NTag :type="getStatusTag(subInstance.status).type">
                      {{ getStatusTag(subInstance.status).text }}
                    </NTag>
                  </NDescriptionsItem>
                  <NDescriptionsItem label="执行时长">
                    {{ formatDuration(subInstance.duration) }}
                  </NDescriptionsItem>
                  <NDescriptionsItem label="开始时间">
                    {{ subInstance.startTime || '-' }}
                  </NDescriptionsItem>
                  <NDescriptionsItem label="结束时间">
                    {{ subInstance.endTime || '-' }}
                  </NDescriptionsItem>
                </NDescriptions>
              </NCard>
            </div>
          </div>
        </div>
      </NSpin>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
